/**
 * created by jsq on 2017/10/18
 */
//API全局设置的新增的编辑
import React from 'react';
import { connect } from 'react-redux';
import {messages} from "share/common";
import { Form, Input,
  InputNumber, Row,
  Col, Button,
  message,
  Select } from 'antd';
import callbackSettingService from 'containers/setting/callback-setting/callback-setting.service';
import "styles/setting/callback-setting/update-callback-setting.scss";
const FormItem = Form.Item;
const Option = Select.Option;

class UpdateCallbackSetting extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      globalSetting: {},
      showParamsType: false,
      listSelectedData: []
    }
  }

  componentWillMount(){}

  componentWillReceiveProps(nextprops){
    this.setState({
      loading: false,
      globalSetting: nextprops.params,
    })
  }
  handleFocus = () => {
    this.refs.blur.focus();
    this.showList(true)
  };

  showList = (flag) => {
    let listSelectedData = [];
    let values = this.props.form.getFieldValue("itemTypeName");
    if (values && values.length > 0) {
      values.map(value => {
        listSelectedData.push(value.value)
      });
    }
    this.setState({
      showItemType: flag,
      listSelectedData
    })
  };

  handleSubmit = (e)=>{
    e.preventDefault();
    this.setState({
      loading: true
    });
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.callbackDatatype = this.state.globalSetting.callbackDatatype;
        values.companyOid = this.state.globalSetting.companyOid;
        values.id = this.state.globalSetting.id;
        values.tenantId = this.props.company.tenantId;
        //todo
        //这个是修改，
        callbackSettingService.updateGlobalSetting(values)
          .then((response)=>{
            this.setState({loading: false});
          if(response.status === 200){
            message.success(`${messages('common.operate.success')}`);
            this.props.form.resetFields();
            this.props.close(true);
          }
        }).catch((e)=>{
          if(e.response){
            message.error(`${messages('common.operate.filed')}, ${e.response.data.message}`);
          }
          this.setState({loading: false});
        });
      }
    });
  };

  onCancel = () =>{
    this.setState({loading: false});
    this.props.form.resetFields();
    this.props.close(false);
  };

  //获取22位随机字符串
  handleRandomString = ()=>{
    let charsArray = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    let maxPos = charsArray.length;
    let string = '';
    for (let i = 0; i < 22; i++) {
      string += charsArray.charAt(Math.floor(Math.random() * maxPos));
    }
    this.props.form.setFieldsValue({"encodingAeskey":string});
    return string;
  };

  //手动输入字符串
  handleInputString = (e)=>{
    let value = e.target.value;
    if(value.length!==22) {
      message.warning(messages('setting.key172'/*encodingAeskey需要22位*/))
    }
  };
  //监听表单值
  handleChange = (e) => {
    if (this.state.loading) {
      this.setState({
        loading: false,
      })
    }
  };

  render(){
    const { getFieldDecorator } = this.props.form;
    const { loading, globalSetting } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 13, offset: 1 },
    };
    return(
      <div className="update-callback-setting">
        <Form onSubmit={this.handleSubmit}
              onChange={this.handleChange}>
          <FormItem {...formItemLayout}
                    label={messages('setting.key152'/*数据格式*/)}>
            {getFieldDecorator('callbackDatatype', {
            })(
              <div className="form-item-1">
                {globalSetting.callbackDatatype}
              </div>
            )}
          </FormItem>
          <Row gutter={30}>
            <Col span={24}>
              <FormItem {...formItemLayout} label="encodingAeskey" >
                {getFieldDecorator('encodingAeskey', {
                  initialValue: globalSetting.encodingAeskey,
                  rules:[
                    {
                      required: true,
                      message: messages("common.please.enter")
                    },
                  ]
                }
                )(
                  <Input onBlur={this.handleInputString} className="call-back-setting-input"
                         placeholder={messages('common.please.enter')} />
                )}
              </FormItem>
            </Col>
            <Col>
              <Button onClick={this.handleRandomString}
                      className="call-back-setting-btn">
                {messages('setting.key168'/*自动生成*/)}
                </Button>
            </Col>
          </Row>
          <Row gutter={30}>
            <Col span={24}>
              <FormItem {...formItemLayout} label="encodingToken" >
                {getFieldDecorator('encodingToken', {
                  initialValue: globalSetting.encodingToken,
                  rules:[
                    {
                      required: true,
                      message: messages("common.please.enter")
                    },
                  ]
                })(
                  <Input className="call-back-setting-input1"
                         placeholder={messages('common.please.enter')} /> /*请输入*/
                )}
              </FormItem>
            </Col>
          </Row>
          <FormItem {...formItemLayout}
                    label={messages('setting.key153'/*系统名称*/)} >
            {getFieldDecorator('sysName', {
              initialValue: globalSetting.sysName,
              rules:[
                {
                  required: true,
                  message: messages("common.please.enter")
                },
              ]
            })(
              <Input placeholder={messages('common.please.enter')} /> /*请输入*/
            )}
          </FormItem>
          <FormItem {...formItemLayout}
                    label={messages('setting.key154'/*管理员名称*/)} >
            {getFieldDecorator('sysAdmin', {
              initialValue: globalSetting.sysAdmin
            })(
              <Input placeholder={messages('common.please.enter')} /> /*请输入*/
            )}
          </FormItem>
          <FormItem {...formItemLayout}
                    label={messages('setting.key155'/*管理员电话*/)} >
            {getFieldDecorator('sysAdminTel', {
              initialValue: globalSetting.sysAdminTel
            })(
              <Input placeholder={messages('common.please.enter')} /> /*请输入*/
            )}
          </FormItem>
          <FormItem {...formItemLayout}
                    label={messages('setting.key157'/*获取超链接时间*/)} >
            {getFieldDecorator('connectionRequestTimeout', {
              initialValue: globalSetting.connectionRequestTimeout
            })(
              <InputNumber
                min={0}
                formatter={value => `${value}ms`}
                parser={value => value.replace('ms', '')}
                placeholder={messages('common.please.enter')} /> /*请输入*/
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key158'/*获取超时时间*/)}>
            {getFieldDecorator('connectTimeout', {
              initialValue: globalSetting.connectTimeout
            })(
              <InputNumber
                min={0}
                formatter={value => `${value}ms`}
                parser={value => value.replace('ms', '')}
                placeholder={messages('common.please.enter')} /> /*请输入*/
            )}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>
              {messages('common.save')}
            </Button>
            <Button onClick={this.onCancel}>
              {messages('common.cancel')}
            </Button>
            <input ref="blur" style={{ position: 'absolute', top: '-9999vh' }}/>
            {/* 隐藏的input标签，用来取消list控件的focus事件  */}
          </div>
        </Form>
      </div>
    )
  }
}
function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

const WrappedUpdateCallbackSetting = Form.create()(UpdateCallbackSetting);
export default connect(mapStateToProps)(WrappedUpdateCallbackSetting);
